<script setup lang="ts">
//import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, onMounted, onBeforeUnmount, watch } from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { oriValidImages, guid } from "@/views/login/utils/validatecard";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import Check from "@iconify-icons/ep/check";
import User from "@iconify-icons/ri/user-3-fill";
import Copyright from "./copyright.vue";
import { getTopMenu, initRouter } from "@/router/utils";
import { useSystemInfo } from "./utils/hook";
//const sysNameFont = ref();
defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
//const myGB=ref();
const ruleFormRef = ref<FormInstance>();
const { logoImage, leftimage, systemName, bgColor, fontColor, isLogin } =
  useSystemInfo();
//验证码igd lk
let validatekey = "";
const validImages = ref(oriValidImages.value);

const { initStorage } = useLayout();
initStorage();

//const { t } = useI18n();
const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "",
  password: "",
  ValidateCode: ""
});
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          userAccount: ruleForm.username,
          userPwd: ruleForm.password,
          validatekey: validatekey,
          ValidateCode: ruleForm.ValidateCode
        })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            initRouter().then(() => {
              router.push(getTopMenu(true).path);
              //console.log(router.getRoutes(), "userLogin");
              message("登录成功", { type: "success" });
            });
            //使用静态路由
            // usePermissionStoreHook().handleWholeMenus([]);
            // addPathMatch();
            // router.push("/");
            // message("登录成功", { type: "success" });
          } else {
            loading.value = false;
            message(res.msg, { type: "error" });
          }
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}
onMounted(async () => {
  window.document.addEventListener("keypress", onkeypress);
  const t = guid();
  validatekey = t;
  validImages.value = oriValidImages.value + t;
});

const reLoadImage = () => {
  const t = guid();
  validatekey = t;
  validImages.value = oriValidImages.value + t;
};
console.log("isLogin", isLogin);
onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
watch(bgColor, () => {
  const myGB = "background-color:" + bgColor.value;
  const fontGB = "color:" + fontColor.value;
  if (!isLogin.value) {
    document.querySelector("body").setAttribute("style", myGB);
    document.querySelector("#sysNameFont").setAttribute("style", fontGB);
    document.querySelector("#boutton").setAttribute("style", fontGB);
  }
});
</script>

<template>
  <div
    v-if="isLogin"
    style="
      height: 300px;
      margin-top: 60px;
      font-weight: bold;
      text-align: center;
    "
  >
    <span>系统正在登录，请稍后...</span>
  </div>
  <div v-if="!isLogin">
    <div class="select-none">
      <!--登录页背景-->
      <!-- <img :src="bg" class="wave" /> -->
      <img alt="logo" class="wave" :src="leftimage" />
      <div class="flex-c absolute right-5 top-3">
        <!-- 主题 -->
        <el-switch
          v-model="dataTheme"
          inline-prompt
          :active-icon="dayIcon"
          :inactive-icon="darkIcon"
          @change="dataThemeChange"
        />
        <!-- 国际化 -->
        <el-dropdown trigger="click">
          <globalization
            class="hover:text-primary hover:!bg-[transparent] w-[20px] h-[20px] ml-1.5 cursor-pointer outline-none duration-300"
          />
          <template #dropdown>
            <el-dropdown-menu class="translation">
              <el-dropdown-item
                :style="getDropdownItemStyle(locale, 'zh')"
                :class="[
                  'dark:!text-white',
                  getDropdownItemClass(locale, 'zh')
                ]"
                @click="translationCh"
              >
                <IconifyIconOffline
                  class="check-zh"
                  v-show="locale === 'zh'"
                  :icon="Check"
                />
                简体中文
              </el-dropdown-item>
              <el-dropdown-item
                :style="getDropdownItemStyle(locale, 'en')"
                :class="[
                  'dark:!text-white',
                  getDropdownItemClass(locale, 'en')
                ]"
                @click="translationEn"
              >
                <span class="check-en" v-show="locale === 'en'">
                  <IconifyIconOffline :icon="Check" />
                </span>
                English
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="login-container">
        <div class="img">
          <!-- <component :is="toRaw(illustration)" /> -->
        </div>
        <div class="login-box">
          <div
            class="login-form"
            style="
              padding: 30px;
              text-align: center;
              background-color: rgb(64 158 255 / 5%);
              border-radius: 10px;
            "
          >
            <!--登录页面logo-->
            <!-- <avatar class="avatar" /> -->

            <img
              alt="logo"
              style="width: 64px; margin: auto"
              :src="logoImage"
            />
            <Motion>
              <h2 id="sysNameFont">
                <span style="font-size: 26px">{{ systemName }}</span>
              </h2>
            </Motion>

            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="loginRules"
              size="large"
            >
              <Motion :delay="100">
                <el-form-item
                  :rules="[
                    {
                      required: true,
                      message: transformI18n($t('login.usernameReg')),
                      trigger: 'blur'
                    }
                  ]"
                  prop="username"
                >
                  <el-input
                    clearable
                    v-model="ruleForm.username"
                    :placeholder="transformI18n($t('login.username'))"
                    :prefix-icon="useRenderIcon(User)"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="150">
                <el-form-item prop="password">
                  <el-input
                    clearable
                    show-password
                    v-model="ruleForm.password"
                    :placeholder="transformI18n($t('login.password'))"
                    :prefix-icon="useRenderIcon(Lock)"
                  />
                </el-form-item>
              </Motion>
              <Motion :delay="200">
                <el-form-item prop="verifyCode">
                  <el-input
                    clearable
                    v-model="ruleForm.ValidateCode"
                    :placeholder="transformI18n($t('login.verifyCode'))"
                    :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                  >
                    <template v-slot:append>
                      <!-- <ReImageVerify v-model:code="imgCode" /> -->
                      <el-image
                        style="width: 100px; height: 30px; cursor: pointer"
                        :src="validImages"
                        @click="reLoadImage"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </Motion>
              <Motion :delay="250">
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  {{ transformI18n($t("login.login")) }}
                </el-button>
              </Motion>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <Copyright />
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.version {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 100px;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
